#!/bin/bash

# 返回码
declare -i ret_ok=0                                     # success
declare -i ret_failed_find_no_software=1                # failed  find install software fail
declare -i ret_failed_stop_sevice_failed=2              # failed  stop process fail
declare -i ret_failed_del_work_path_err=3                # failed  delete work dir error

WORK_PATH="/opt/middleware/AtlasEdge"
SCRIPT_PATH="/opt/middleware/AtlasEdge/software/edge_site/edge_manager/src/script"
CORE_CONFIG_FILE="software/edge_core/conf/edgecore.yaml"
MODELFILE_DIR="/var/lib/docker/modelfile/"

. ${SCRIPT_PATH}/common.sh
. ${SCRIPT_PATH}/log_util.sh

function usage() {
    echo "uninstall -- uninstall software"
    echo "parameters:"
    echo "usage: "
    echo "     uninstall"
}

function checkWorkPath()
{   
    #if software and config not exist，so it is not install, no uninstall
    if [ ! -e "${WORK_PATH}/software" -o ! -e "${WORK_PATH}/config" ]; then
         logger_Warn "atlasEdge is not installed."
         return 1
    fi
    
    return 0
}

main(){
    
    if [ "$#" -gt 0 ]; then
        if [ "$1" == "-h" ]; then
            usage
            return 0
        fi
    fi

    #check work path install
    checkWorkPath
    ret=$?
    if [ ${ret} -ne 0 ]; then
        return ${ret_failed_find_no_software}
    fi
    
    bash ${SCRIPT_PATH}/stop.sh
    ret=$?
    if [ ${ret} != 0 ];then
        logger_Warn "stop service failed ret:$ret continue"
        #return $ret_failed_stop_sevice_failed
    fi

    TlsCaFile=`cat ${WORK_PATH}/${CORE_CONFIG_FILE} | grep tlsCaFile | awk '{print $2}'`
    if [ "$TlsCaFile" != "" -a -f "$TlsCaFile" ];then
        rm -f $TlsCaFile
    fi

    containerinfo=`docker ps -a -q`
    modelfileCount=`ls -l $MODELFILE_DIR 2>/dev/null | grep "^d" | wc -l`
    if [ "$containerinfo" != "" -o $modelfileCount -ne 0 ];then
        logger_Debug "Notice: There may be containers or modelfiles remain in $(basename ${MODELFILE_DIR}). Please clear them if you don't need anymore"
    fi

    # remove privilege setting
    privilege_cmds_file="${SCRIPT_PATH}/privilege_cmd_list.txt"
    cat ${privilege_cmds_file} | while read line;
    do
        if [[ -z "$line" ]] || [[ "$line" =~ ^#.* ]]; then
            continue
        fi
        sed -i "/${line//\//\\/}/d" /etc/sudoers
    done

    #uninstall work path
    rm -rf "${WORK_PATH}"
    if [ $? -ne 0 ]; then
         logger_Warn "uninstall atlasEdge failed: rm -rf $(basename ${WORK_PATH}) failed."
         return ${ret_failed_del_work_path_err}
    fi

    #uninstall success
    logger_Info "uninstall atlasEdge successfully."
    return ${ret_ok}
}

main "$@"
RESULT=$?
exit $RESULT
